/**
 * 腾讯云存储js方法封装处理
 * zhanghang
 */
var cosUpload = (function () {

    var config = {
        Bucket: 'mioumanage-1259471224',
        Region: 'ap-chengdu'
    };

    function randomCoding(){
        var result = [];
        var  n = 4;
        for(var i=0; i<n ;i++){
            var ranNum = Math.ceil(Math.random() * 25);
            result.push(String.fromCharCode(65+ranNum));
        }
        return result.join('');
    }


    function getRandFileName(filePath) {
        var extIndex = filePath.lastIndexOf('.');
        var extName = extIndex === -1 ? '' : filePath.substr(extIndex);
        var newTime = jQuery.common.dateFormat(new Date, 'yyyy/MM/dd') + '/';
        var randomNum = parseInt('' + Date.now() + Math.floor(Math.random() * 900 + 100), 10).toString(36)
        return newTime + randomNum + randomCoding() + extName;
    }



    function setProgress(evt, $el) {
        var $progressBar = $el.find(".progress-bar")
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        $progressBar.width(percentComplete+"%");
        $progressBar.html(percentComplete+"%");
    }

    function progressError($el) {
        var $progressBar = $el.find(".progress-bar")
        var progressErrorClass =  'progress-bar bg-danger progress-bar-danger';
        $progressBar.attr("class", progressErrorClass)

        var closeButton = '<button type="button" class="close kv-error-close" aria-label="Close">\n' +
                '  <span aria-hidden="true">&times;</span>\n' +
                '</button>';
        var errMsg = '<ul><li>文件上传失败.</li></ul>'
        var $error = $el.find(".kv-fileinput-error")
        $error.fadeIn(100);
        $error.html(closeButton + errMsg);
        $error.find('.kv-error-close').on('click', function () {
            setTimeout(function () {
                $error.html("");
                $error.fadeOut('slow');
            }, 100);
        });
    }


    var cos = new COS({
        getAuthorization: function(options, callback) {
            var authorization = COS.getAuthorization({
                SecretId: 'AKIDHJRJ0TwdJhp30hBHBuOdz4shHacNqXtx', //密钥ID
                SecretKey: 'HI2VorhiDSP6X6UzaKpRnbEWYJUPRntj', //密钥
                Method: options.Method,
                Key: options.Key,
                Query: options.Query,
                Headers: options.Headers,
                Expires: 60,
            });
            callback(authorization);
        },
    });

    var putPath =  function(event, file) {
        file.prefix = file.prefix ? file.prefix : 'imagelist/'
        var Key = file.prefix + getRandFileName(file.name);
        var $element = $(event.currentTarget).closest(".file-input")
        var $progress = $element.find(".kv-upload-progress")
        cos.putObject({
            Bucket: config.Bucket,
            Region: config.Region,
            Key: Key,
            Body: file,
            onTaskReady: function(tid) {
                console.log('onTaskReady', tid);
                $element.addClass('file-uploading');
                $progress.show()
            },
            onProgress: function(progressData) {
                setProgress(progressData, $progress)
            },
        }, function(err, data) {
            $element.removeClass('file-uploading');
            if (err){
                console.log(err)
                progressError($element)
                return
            }
            $element.prev().val("https://" + data.Location)
        });
    }



    return {
        putPath: putPath
    }
})()
